<template>
  <div>
    <!--搜索框-->
    <div style="margin-top: 10px">
      <el-input v-model="keywords" placeholder="搜索订单..." prefix-icon="el-icon-search"
                style="width: 220px;margin-right: 10px" size="medium"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="doSearch" size="medium">搜索</el-button>
    </div>
    <div class="user-container">
      <!--历史订单主页面-->
      <el-card class="user-card" v-for="(history,index) in tableData" :key="index">
        <div slot="header" class="clearfix">
          <span>订单详情</span>
          <el-button style="float: right; padding: 3px 0"
                     type="text" class="el-icon-edit" @click="openComment(history)">评价</el-button>
        </div>
        <div>
          <div class="img-container">
            <el-tooltip class="item" effect="dark" content="点我查看订单详情！" placement="top">
              <img :src="history.imgurl" class="avatar_imgs" @click="showEditView(history)">
            </el-tooltip>

            <div cLass="userinfo-container">
              <el-descriptions :column="3" size="small">
                <el-descriptions-item label="租赁编号">{{history.rent_id}}</el-descriptions-item>
                <el-descriptions-item label="数量">{{history.number}}</el-descriptions-item>
                <el-descriptions-item label="价格">{{history.day_price===''?history.single_price+'/每小时':history.day_price+'/每天'}}（总价格：{{history.tol_rent_price}}元）</el-descriptions-item>
                <el-descriptions-item label="承租方用户名">{{history.username}}</el-descriptions-item>
                <el-descriptions-item label="租赁时间段">{{history.starttime}}——{{history.endtime}}</el-descriptions-item>
                <el-descriptions-item label="租赁状态">
                  <el-switch
                    disabled
                    v-model="status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="已完成">
                  </el-switch>
                </el-descriptions-item>
                <el-descriptions-item label="下单时间">{{history.rent_time}}</el-descriptions-item>
                <!--<el-descriptions-item label="收货地址">{{history.order_address}}</el-descriptions-item>-->
              </el-descriptions>
            </div>
          </div>
        </div>
      </el-card>
      <!--点击图片弹窗-->
      <el-dialog
        :visible.sync="dialogFormVisible"
        width="1000px">
        <!--商品信息-->
        <el-descriptions class="margin-top" title="商品信息" :column="3" size="medium" border>
          <el-descriptions-item>
            <template slot="label">
              租赁方用户ID
            </template>
            {{goodList.user_id}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              租赁方用户名
            </template>
            {{goodList.username}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品id
            </template>
            {{goodList.good_id}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品实物图
            </template>
            <template>
              <el-image style="width: 40px" :src="goodList.imgurl" :preview-src-list="[goodList.imgurl]">
              </el-image>
            </template>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品类型
            </template>
            {{goodList.category}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品名称
            </template>
            {{goodList.good_name}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              价格/小时
            </template>
            {{goodList.rent_price_hour}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              价格/天
            </template>
            {{goodList.rent_price_day}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              品牌
            </template>
            {{goodList.brand}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              支付状态
            </template>
            <el-tag size="small" :type="goodList.paystate=='0'?'danger':goodList.paystate=='2'?'':'success'">
              {{goodList.paystate==0?'未支付':'已支付'}}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              发货状态
            </template>
            <el-tag size="small" :type="goodList.rent_state=='0'?'danger':goodList.rentState=='2'?'':'success'">
              {{goodList.rentState==0?'未发货':goodList.rentState==1?'已发货':'已收货'}}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品描述
            </template>
            {{goodList.description}}
          </el-descriptions-item>
        </el-descriptions>
          <el-descriptions class="margin-top" title="收货人信息" :column="3" size="medium" border>
          <el-descriptions-item>
            <template slot="label">
              收货人
            </template>
            {{orderAddress.userName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              手机号
            </template>
            {{orderAddress.contactPhone}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              订单地址
            </template>
            {{orderAddress.takeAddres}}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
      <!--添加或修改评价弹窗-->
      <el-dialog :visible.sync="commentVisible" :title="edit ? '修改评价' : '添加评价'" width="600px">
        <el-form ref="elForm" :model="commentData" :rules="rules" size="medium" label-width="100px">
          <el-form-item label="商品相符" prop="star">
            <el-rate v-model="commentData.star" :max='5' allow-half show-score></el-rate>
          </el-form-item>
          <el-form-item label="服务态度" prop="manner">
            <el-rate v-model="commentData.manner" :max='5' allow-half show-score></el-rate>
          </el-form-item>
            <el-form-item label="图片上传">
              <el-upload
                ref="avatar"
                action="string"
                :http-request="uploadImg"
                :on-remove="handleRemove"
                list-type="picture">
                <el-button size="small" type="primary" plain>上传商品实物图</el-button>
                <div slot="tip" class="el-upload__tip" style="color: #1a1a1a">只能上传jpg/png文件，且不超过500kb</div>
                <div slot="tip">
                  <img v-if="hidden" :src=commentData.img alt="" style="width: 80px;height: 80px">
                </div>
              </el-upload>
            </el-form-item>
          <el-form-item label="评论内容" prop="review">
            <el-input v-model="commentData.review" type="textarea" placeholder="请输入评论评论内容"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="commentVisible=false">取消</el-button>
          <el-button type="primary" @click="sureComment">确定</el-button>
        </div>
      </el-dialog>
      <!--已评价弹窗-->
      <el-dialog :visible.sync="finishVisible" title="已评价">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="商品相符" label-class-name="my-label" content-class-name="my-content">{{commentData.star}}</el-descriptions-item>
          <el-descriptions-item label="商品相符">{{commentData.manner}}</el-descriptions-item>
          <el-descriptions-item label="评论内容">{{commentData.review}}</el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              商品实物图
            </template>
            <template>
              <el-image style="width: 40px" :src="commentData.img" :preview-src-list="[commentData.img]">
              </el-image>
            </template>
          </el-descriptions-item>
        </el-descriptions>
        <div slot="footer">
          <el-button size="mini" type="danger" @click="deleteComment" plain>删除</el-button>
          <el-button size="mini" type="warning" @click="updateComment" plain>修改</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'historyGood',
    data(){
      return{
        user:JSON.parse(window.sessionStorage.getItem('user')),
        tableData:[],
        goodList:{},
        keywords:'',
        rentState:2,
        status:true,
        dialogFormVisible:false,
        commentVisible:false,
        finishVisible:false,
        commentData:{
          goodId:undefined,
          userId:undefined,
          star:undefined,
          review:'',
          manner:undefined,
          img:'',
        },
        orderAddress:{},
        edit:false,
        hidden:false,
        rules: {
          star: [{
            required: true,
            message: '商品相符不能为空',
            trigger: 'change'
          }],
          manner: [{
            required: true,
            message: '服务态度不能为空',
            trigger: 'change'
          }],
          review: [{
            required: true,
            message: '请输入评论评论内容',
            trigger: 'blur'
          }],
        },
      }
    },
    mounted(){
      this.initTable();
    },
    methods:{
      // 删除评价
      deleteComment(){
        this.$confirm('确定删除该评价?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest('/system/cfg/comment/'+this.commentData.goodId+"?userId="+this.user.userId).then(resp=>{
            this.$notify.success({ title: '成功', message: resp.message });
            this.this.finishVisible=false
            this.initTable();
          })
        }).catch(() => {
          this.$notify.info({ title: '消息', message: '已取消删除' });
        });
      },
      // 点击修改按钮事件
      updateComment(){
        this.hidden=true
        this.finishVisible=false
        this.commentVisible=true

      },
      // 确定按钮事件
      sureComment(){
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          // TODO 提交表单
          // 调用修改评论接口
          if(this.edit===true){
            this.putRequest('/system/cfg/comment/',this.commentData).then(resp=>{
              if (resp){
                this.commentVisible=false
                this.initTable();
                this.$notify.success({ title: '成功', message: resp.message });
              }
            })
          }
          // 调用添加评论接口
          else{
            this.hidden=false
            console.log(this.commentData)
            this.postRequest('/system/cfg/comment/add',this.commentData).then(resp=>{
              if (resp){
                this.commentVisible=false
                this.initTable();
                this.$notify.success({ title: '成功', message: resp.message });
              }
            })
          }
        })
      },
      // 点击评论事件
      openComment(data){
        // 查询当前商品是否有评价
        this.getRequest('/system/cfg/comment/selectOne/?goodId='+data.good_id+"&&userId="+this.user.userId).then(resp=>{
          if (resp){
            // 如果有，则展示评论详情页finishVisible
            this.commentData=resp
            this.finishVisible=true
            //调用修改的方法
            this.edit=true
          }else{
            // 否则，展示评论页面
            this.commentVisible=true
            // 添加评论
            this.commentData.star='';
            this.commentData.review='';
            this.commentData.manner='';
            this.commentData.img='';
            this.hidden=false
            this.commentData.goodId=data.good_id
            this.commentData.userId=this.user.userId
          }
        })
      },
      // 出租方的历史订单，根据出租人的id和订单已完成的状态查询
      initTable () {
        let myUseId = parseInt(this.user.userId);
        let url = '/rent/data/rentHistory/?myUseId='+myUseId+'&&rentState='+this.rentState;
        this.postRequest(url).then(resp => {
          if (resp) {
            console.log(resp);
            this.tableData=resp;
          }
        })
      },
      // 点击图片事件
      showEditView(data){
        console.log(data.order_address)
        // 根据地址id查询订单地址
        this.getRequest('/rent/addressById/'+data.order_address).then(resp => {
          if (resp) {
            this.orderAddress=resp;
          }
        })
        // 获取按钮点击的商品信息
        Object.assign(this.goodList,data);
        // 存储商品id到commentData修改的对象
        this.commentData.goodId=this.goodList.good_id
        // dialogFormVisible商品详情页
        this.dialogFormVisible=true;
      },
      doSearch(){
        this.initTable();
      },
      //上传图片
      uploadImg(item) {
        // 如果上传图片，删除之前的图片
        if (this.commentData.img){
          this.handleRemove()
        }
        let formData = new FormData()
        formData.append('file', item.file)
        this.hidden=false;
        this.postRequest('/good/data/uploadImgFile',formData).then(resp => {
          if (resp) {
            console.log(resp);
            this.commentData.img=resp.obj;
          }
        })
      },
      //删除图片
      handleRemove() {
        let formData = new FormData()
        formData.append('file', this.commentData.img)
        this.postRequest('/good/data/deleteImgFile',formData).then(resp => {
          if (resp) {
            console.log(resp);
          }
        })
      },
    }
  }

</script>

<style>
  .user-container{
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    margin-top: 30px;
  }
  .user-card{
    width: 100%;
    margin-bottom: 20px;
  }
  .avatar_imgs{
    width: 80px;
    height: 80px;
    border-radius: 72px;
    margin-right: 20px;
  }
  .img-container{
    width: 100%;
    display: flex;
    margin-left: 10px;
  }
  .userinfo-container{
    font-size: 14px;
    color: cornflowerblue;
  }
  .my-label {
    background: #E1F3D8;
  }

  .my-content {
    background: #FDE2E2;
  }

</style>
